package com.pig4cloud.pig.generator.utils;
import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;

import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;

import java.util.Map;
//TODO 七牛云图片存储
public class QiniuUtil {

	//    外链域名
	public static String qiniu_url = "qwbv4ua6s.hn-bkt.clouddn.com";


	//    AccessKey
	public static String access_key = "CaUTwd70doMPY13DiEXLiFeNxfpfGjpREfx2j-ov";

	//    SecretKey
	public static String secret_key = "aD5Fe5DOc3TwtFGeadOKEeUPb9FGPWNNjho6RoB_";

	//    存储空间名称
	public static String bucketName = "zzlong";


	//    上传文件
	public static String uploadQiNiu(byte[] file, String fileName) {

//        构造一个带指定Zone对象的配置了，  Zone.zone0() 代表华东区   Zone.zone1() 代表华北区  Zone.zone2() 代表华南区
		Configuration cfg = new Configuration(Zone.zone2());

//       其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);

//      默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = null;
		Auth auth = Auth.create(access_key, secret_key);

		String token = auth.uploadToken(bucketName);


		try {
			Response response = uploadManager.put(file, fileName, token);
//            解析上传成功的结果
			String bodyString = response.bodyString();

			Map map = JSON.parseObject(bodyString, Map.class);

			String hash = (String) map.get("key");

			System.out.println("hash======" + hash);


			System.out.println("1111111111");
			System.err.println(hash);

			System.out.println("url:" + qiniu_url + fileName);

			System.err.println("http://" + qiniu_url + "/" + fileName);


			return "http://" + qiniu_url + "/" + fileName;


		} catch (QiniuException e) {
			Response r = e.response;
			System.err.println(r.toString());
			System.out.println("上传失败");
			try {
				System.err.println(r.bodyString());
				return null;
			} catch (QiniuException ex2) {
				//ignore
				e.printStackTrace();
				return null;
			}
		}
	}
}